import { defineStore } from 'pinia'
import router from '@/router'
// import { computed } from 'vue'
const useRouterStore = defineStore('router', () => {

  // 浏览过的页面
  const visitedViews = ref(JSON.parse(localStorage.getItem('VisitedViews')) || [])
  const activeViews = ref(router.currentRoute.value)

  const setVisitedViews = (views) => {
    visitedViews.value = views
  }


  //添加浏览的页面
  const addVisitedViews = (router) => {
    switchCurrentViews(router)
    const isExist = visitedViews.value.some(item => router.name === item.name)
    if (!isExist) visitedViews.value.push(router)
    sortVisitedViews()
    saveLocalStorageVisitedViews()
  }

  //删除指定的浏览页面
  const removeVisitedViews = (removeRouter) => {
    let curRouterIndex = visitedViews.value.findIndex(item => item.path !== removeRouter.path)
    visitedViews.value = visitedViews.value.filter(item => item.path !== removeRouter.path)

    if (curRouterIndex >= visitedViews.value.length) {
      curRouterIndex = visitedViews.value.length - 1
    }

    activeViews.value = visitedViews.value[curRouterIndex]

    router.push(activeViews.value.path)
    saveLocalStorageVisitedViews()
  }

  //切换浏览页 
  const switchCurrentViews = (views) => {
    activeViews.value = views
  }

  //让‘首页一直第一’
  const sortVisitedViews = () => {
    visitedViews.value = visitedViews.value.filter(item => item.name === 'home').concat(visitedViews.value.filter(item => item.name !== 'home'))
  }


  //面包屑
  const breadcrumbs = ref([])

  const getNewBreadCrumbs = (matched) => {
    let match = matched
    if (match[0]?.path === '/') {
      match = match.slice(1)
    }
    match = match.filter(item => item.meta.title)
    breadcrumbs.value = match
  }

  //本地缓存浏览过的路径
  const saveLocalStorageVisitedViews = () => {
    localStorage.setItem('VisitedViews', JSON.stringify(visitedViews.value))
  }

  //本地缓存删除浏览路径
  const removeLocalStorageVisitedViews = () => {
    localStorage.removeItem('VisitedViews')
    visitedViews.value = []
  }

  // window.addEventListener()



  return {
    visitedViews,
    activeViews,
    addVisitedViews,
    removeVisitedViews,
    switchCurrentViews,
    breadcrumbs,
    getNewBreadCrumbs,
    removeLocalStorageVisitedViews,
    setVisitedViews
  }
})

export default useRouterStore